package cn.juque.redoctopus.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.juque.luceneplus.dto.SearchAfterResultDTO;
import cn.juque.luceneplus.service.DocumentPlusService;
import cn.juque.redoctopus.api.constants.LogIndexEnum;
import cn.juque.redoctopus.bo.LogBO;
import cn.juque.redoctopus.bo.LogDataGridBO;
import cn.juque.redoctopus.bo.LogSearchBO;
import cn.juque.redoctopus.bo.field.FieldDocBO;
import cn.juque.redoctopus.convert.FieldDocConverter;
import cn.juque.redoctopus.convert.SearchAfterRequestDTOConverter;
import cn.juque.redoctopus.service.ILogService;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.apache.lucene.document.Document;
import org.apache.lucene.search.FieldDoc;
import org.apache.lucene.search.ScoreDoc;
import org.springframework.stereotype.Service;

/**
 * @author nuoka
 * @version 1.0.0
 * <li></li>
 * @date 2021/11/7 20:45
 **/
@Service("logService")
public class LogServiceImpl implements ILogService {

    @Resource
    private DocumentPlusService documentPlusService;

    /**
     * 滚动式日志查询
     *
     * @param logSearchBO LogSearchBO
     * @return LogDataGridBO
     */
    @Override
    public LogDataGridBO<LogBO> listLog(LogSearchBO logSearchBO) throws IOException {
        SearchAfterResultDTO searchAfterResultDTO = this.documentPlusService.searchByAfter(SearchAfterRequestDTOConverter.toSearchAfterRequestDTO(logSearchBO));
        List<Document> docList = searchAfterResultDTO.getResult();
        List<LogBO> logBOList = docList.stream().map(t -> {
            LogBO bo = new LogBO();
            bo.setServiceNo(t.get(LogIndexEnum.SERVICE_NO.getCode()));
            bo.setServiceName(t.get(LogIndexEnum.SERVICE_NAME.getCode()));
            bo.setLevel(t.get(LogIndexEnum.LEVEL.getCode()));
            bo.setMessage(t.get(LogIndexEnum.MESSAGE.getCode()));
            bo.setThrowable(t.get(LogIndexEnum.THROWABLE.getCode()));
            long logTime = Long.parseLong(t.get(LogIndexEnum.LOG_TIME.getCode()));
            if(ObjectUtil.isNotEmpty(logTime)) {
                bo.setTimestamp(new Date(logTime));
            }
            bo.setIp(t.get(LogIndexEnum.IP.getCode()));
            return bo;
        }).collect(Collectors.toList());
        ScoreDoc scoreDoc = searchAfterResultDTO.getLastDoc();
        FieldDocBO fieldDocBO = FieldDocConverter.toFieldDocBO((FieldDoc) scoreDoc);
        return new LogDataGridBO<>(logBOList, searchAfterResultDTO.getTotalHis(), fieldDocBO);
    }
}
